Passed
Push — development ( e131c7...d0a4d7 )
by Peter
05:27 queued 13s
created

utils.ts ➔ isGuarded   A

Complexity

Conditions 4

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 21
dl 0
loc 34
rs 9.376
c 0
b 0
f 0
1
import { CanActivate } from '@nestjs/common';
2
import { JwtService } from '@nestjs/jwt';
3
import { Test } from '@nestjs/testing';
4
import { JwtPayload } from 'src/auth/types/jwt-payload.interface';
5
import { AppModule } from './../src/app.module';
6
7
// is guarded is a copy from stackoverflow / stackexchange
8
/**
9
 * Checks whether a route or a Controller is protected with the specified Guard.
10
 * @param route is the route or Controller to be checked for the Guard.
11
 * @param guardType is the type of the Guard, e.g. JwtAuthGuard.
12
 * @returns true if the specified Guard is applied.
13
 */
14
function isGuarded(
15
  route: ((...args: any[]) => any) | (new (...args: any[]) => unknown),
16
  guardType: new (...args: any[]) => CanActivate,
17
) {
18
  const guards: any[] = Reflect.getMetadata('__guards__', route);
19
20
  if (!guards) {
21
    throw Error(
22
      `Expected: ${route.name} to be protected with ${guardType.name}\nReceived: No guard`,
23
    );
24
  }
25
26
  let foundGuard = false;
27
  const guardList: string[] = [];
28
  guards.forEach((guard) => {
29
    guardList.push(guard.name);
30
    // console.log(guard.name)
31
    if (guard.name === guardType.name) foundGuard = true;
32
  });
33
34
  if (!foundGuard) {
35
    throw Error(
36
      `Expected: ${route.name} to be protected with ${guardType.name}\nReceived: only ${guardList}`,
37
    );
38
  }
39
  return true;
40
}
41
42
// sub: user.githubId,
43
// username: user.username,
44
// email: user.email,
45
// roles: user.roles
46
function generateToken(user: JwtPayload) {
47
  const secret = process.env.JWT_SECRET || 'your-test-secret';
48
  const jwtService = new JwtService({
49
    secret: process.env.JWT_SECRET,
50
  });
51
  const token = jwtService.sign(user);
52
  return token;
53
}
54
55
const adminUser = {
56
  sub: '67890',
57
  username: 'adminuser',
58
  email: '[email protected]',
59
  roles: ['admin'],
60
};
61
const standardUser = {
62
  sub: '12345',
63
  username: 'testuser',
64
  email: '[email protected]',
65
  roles: ['user'],
66
};
67
68
function generateTestTokens() {
69
  const adminToken = generateToken(adminUser);
70
  const userToken = generateToken(standardUser);
71
72
  return {
73
    adminToken,
74
    userToken,
75
  };
76
}
77
78
async function initTestApp() {
79
  const moduleFixture = await Test.createTestingModule({
80
    imports: [AppModule],
81
  }).compile();
82
83
  const app = moduleFixture.createNestApplication();
84
  await app.init();
85
86
  // Initialize test data
87
  const userRepo = app.get('UserRepository');
88
  await userRepo.save([
89
    {
90
      githubId: '12345',
91
      username: 'testuser',
92
      email: '[email protected]',
93
      roles: ['user'],
94
    },
95
    {
96
      githubId: '67890',
97
      username: 'adminuser',
98
      email: '[email protected]',
99
      roles: ['admin'],
100
    },
101
  ]);
102
103
  return app;
104
}
105
106
function removeTimestamps(users: any[]) {
107
  return users.map(({ createdAt, updatedAt, ...rest }) => rest);
108
}
109
110
export { isGuarded, generateToken, removeTimestamps, generateTestTokens, initTestApp };
111